import { gePortalUserMenu } from '@/api/user'
import menuImages from '@/assets/js/menuImages'
import menuImagesGrey from '@/assets/js/menuImagesGrey'
import { deepCopy } from '@/utils'
import { constantRoutes } from '@/router'
// 菜单图标
function getMenuImage(menu) {
  const icon = menu.icon
  const src = menuImages[icon]
  const srcset = `${menuImages[icon + '2x']} 2x`
  const srcGrey = menuImagesGrey[icon]
  const srcsetGrey = `${menuImagesGrey[icon + '2x']} 2x`
  menu.imgSrcGrey = srcGrey
  menu.imgSrcsetGrey = srcsetGrey
  menu.imgSrc = src
  menu.imgSrcset = srcset
  return menu
}
// 查找指定的sub-menu
function findSubMenu(menuTree, indexPath, selected) {
  for (const menu of menuTree) {
    if (selected) {
      menu.selected = false
    }
    if (indexPath.includes(menu.menuId) || (menu.url !== null && indexPath.includes(menu.url))) {
      menu.selected = selected
    }
    if (menu.childrens && menu.childrens.length > 0) {
      findSubMenu(menu.childrens, indexPath, selected)
    }
  }
}
// 查找路径
function findIndexPath(menuTree, index) {
  const t = []
  for (const menu of menuTree) {
    if (index === menu.menuId || (menu.url !== null && index === menu.url)) {
      t.push(menu.menuId)
      return t
    }
    if (menu.childrens && menu.childrens.length > 0) {
      const ct = findIndexPath(menu.childrens, index)
      if (ct.length > 0) {
        t.push(...ct, menu.menuId)
      }
    }
  }
  return t
}
/**
 * 判断指定菜单子级是否包含指定菜单编码
 * @param menus 菜单对象
 * @param code 菜单编码
 * @returns {Boolean}
 */
function hasChildMenuCode(menus, code) {
  if (menus.childrens && menus.childrens.length > 0) {
    return menus.childrens.some(menu => menu.menuCode === code)
  } else {
    return true
  }
}

/**
 * 判断菜单集合中是否包含当前菜单编码
 * @param menuList 菜单集合
 * @param code 当前菜单编码
 * @returns {Boolean}
 */
export function findMenusTree(menuList, code) {
  if (!menuList || !code) {
    return false
  }
  const result = false
  for (const menu of menuList) {
    const tmp = { ...menu }
    if (hasChildMenuCode(tmp, code)) {
      return true
    } else {
      if (tmp.childrens && tmp.childrens.length) {
        return findMenusTree(tmp.childrens, code)
      }
    }
  }
  return result
}

/**
 * 获取当前菜单编码所对应的三级菜单（左侧菜单）
 * @param menuList 所有菜单集合
 * @param {string} defaultCode 当前菜单编码
 */
export function getDefaultMenuTree(menuList, defaultCode) {
  if (menuList.length === 0) {
    return null
  }
  if (!defaultCode) {
    // 若菜单编码不存在，则返回菜单序列中第一个菜单的第一个二级子菜单
    if (menuList[0].childrens && menuList[0].childrens.length) {
      return menuList[0].childrens[0]
    } else {
      return null
    }
  }
  // 遍历一级菜单，若当前菜单编码为一级菜单，则返空
  const firstMenu = menuList.filter(menu => menu.menuCode === defaultCode)
  if (firstMenu.length) {
    return null // firstMenu[0]
  }

  let defaultMenu = null
  for (const mainMenu of menuList) {
    const childMenu = mainMenu.childrens.filter(menu => menu.menuCode === defaultCode)
    // 若二级菜单中包含有当前菜单编码，则返空
    if (childMenu.length) {
      return null
    }

    // 遍历二级菜单
    for (const menu of mainMenu.childrens) {
      const tmp = { ...menu }
      const hasCode = hasChildMenuCode(tmp, defaultCode)
      if (hasCode) { // 若下一级菜单包含当前菜单编码,则返回当前菜单
        defaultMenu = tmp
        break
      } else {
        // 判断当前菜单的所有下级菜单中是否包含当前菜单编码
        const childHasCode = findMenusTree(tmp.childrens, defaultCode)
        if (childHasCode) {
          defaultMenu = tmp
          break
        }
      }
    }

    if (defaultMenu) {
      break
    }
  }

  return defaultMenu
}

/**
 * 根据路由生成菜单
 * @param menuList 后台返回的菜单
 * @param routes 路由
 */
export function genMTByRoutes(menuList, routes) {
  // FIXME: 暂时直接根据路由生成
  const menuTree = []
  for (const item of routes) {
    menuTree.push(
      {
        menuName: item.meta.title,
        url: item.path || '',
        icon: item.meta.icon,
        hidden: item.meta.hidden,
        level: 6,
        menuCode: Math.floor(Math.random() * 1000).toString(),
        childrens: item.children && item.children.length > 0 ? genMTByRoutes(menuList, item.children) : []
      }
    )
  }
  return menuTree
}
// 找菜单
// 获取菜单码
function findMenuCode(path, menuTree) {
  for (const menu of menuTree || []) {
    if (menu.url === path) {
      return menu.menuCode
    }
    if (menu.childrens instanceof Array) {
      const t = findMenuCode(path, menu.childrens)
      if (t) {
        return t
      }
    }
  }
  return ''
}
const regPrefix = new RegExp(`^/${process.env.VUE_APP_PORTALCODE}|/`, 'g')
// 处理菜单数据，区分本地路由和外部链接
function handleMenuData(menu) {
  for (const item of menu) {
    if (item.url) {
      const url = item.url.replace(regPrefix, '')
      if (!matchLocalRoute(url, constantRoutes)) {
        item.openType = 2
      }
    }
    if (item.childrens) {
      handleMenuData(item.childrens)
    }
  }
  return menu
}

function matchLocalRoute(url, routes) {
  for (const item of routes) {
    if (item.path && item.path !== '/') {
      const t = item.path.replace(regPrefix, '')
      if (url.includes(t)) {
        return true
      }
    }
    if (item.children) {
      const t = matchLocalRoute(url, item.children)
      if (t) {
        return t
      }
    }
  }
  return false
}

const state = {
  menuList: [], // 所有菜单
  menuTree: []// 左侧菜单树
}

const mutations = {
  SET_MENULIST: (state, menuList) => {
    state.menuList = menuList || []
  },
  SET_MENUTREE: (state, menuTree) => {
    state.menuTree = menuTree.map(e => {
      return getMenuImage(e)
    })
  },
  // 设置激活菜单图标
  SET_OPEN_MENU(state, indexPath) {
    const menuTree = state.menuTree
    if (!(indexPath instanceof Array)) {
      indexPath = findIndexPath(menuTree, indexPath)
    }
    findSubMenu(menuTree, indexPath, true)
    state.menuTree = deepCopy(menuTree)
  },
  // 设置关闭菜单图标
  SET_CLOSE_MENU(state, indexPath) {
    const menuTree = state.menuTree
    findSubMenu(menuTree, indexPath, false)
    state.menuTree = deepCopy(menuTree)
  }
}

const actions = {
  // 获取门户菜单数据
  getPortalMenu({ commit, state, dispatch }, defaultMenuCode) {
    return new Promise((resolve, reject) => {
      gePortalUserMenu(state.token).then(response => {
        let data = response.data || []
        if (/^cc/.test(location.host)) {
          data = handleMenuData(data)
        }
        // const defualtMenu = getDefaultMenuTree(data, defaultMenuCode) // 默认左侧菜单列
        // commit('SET_MENULIST', data)
        // commit('SET_MENUTREE', defualtMenu ? defualtMenu.childrens || [] : [])
        // resolve(defualtMenu)
        // 修改
        commit('SET_MENULIST', data)
        commit('SET_MENUTREE', data || [])
        dispatch('getCallBarButtonList', state.menuTree, { root: true })
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  generateMenuTree({ commit }, data) {
    return new Promise(resolve => {
      commit('SET_MENUTREE', data)
      resolve(data)
    })
  },

  // 获取菜单码
  async getMenuCode({ state }, { path, fromMenuCode }) {
    const menuCode = findMenuCode(path, state.menuTree)
    if (menuCode) {
      return await Promise.resolve(menuCode)
    // eslint-disable-next-line brace-style
    }
    // else if (fromMenuCode) {
    //   return await Promise.resolve(fromMenuCode)
    // }
    else {
      // return await Promise.reject()
      return await Promise.resolve(undefined)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
